package com.taylor.community.controller.interceptor;

import com.taylor.community.entity.LoginTicket;
import com.taylor.community.entity.User;
import com.taylor.community.service.UserService;
import com.taylor.community.util.CookieUtil;
import com.taylor.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中获取登录凭证 CookieUtil是自己封装的通过request来获取cookie的类
        String ticket = CookieUtil.getValue(request,"ticket");
        if(ticket != null){
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            //检查凭证是否有效
            if(loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())){
                User user= userService.findUserById(loginTicket.getUserId());
                //本次请求中持有的用户
                hostHolder.setUsers(user);
                //构建用户认证的结果，并存入SecurityContext，以便Security进行授权(密码认证的方式)
                Authentication authentication = new UsernamePasswordAuthenticationToken(
                        user,user.getPassword(),userService.getAuthorities(user.getId())
                );
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if(user != null && modelAndView != null){
            //postHandle在controller之后模板引擎调用之前被调用（在此之前将数据存到model中）
            modelAndView.addObject("loginUser",user);
        }
    }
    //视图渲染之后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求结束后 将内存中的相应数据给清除
        hostHolder.clear();//清除每次请求获取到的user对象
//        //清除每次请求结束的认证结果 避免内存泄露 只要是登录状态（ticket!=null） 每次请求都会存认证结果到SecurityContext
        SecurityContext context = SecurityContextHolder.getContext();
        SecurityContextHolder.clearContext();
    }
}
